package com.project.web.controller.sys;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.common.UserPwd;
import com.project.service.sys.CacheService;
import com.project.common.ConfigBean;
import com.project.web.controller.BaseController;
import com.project.entity.sys.Department;
import com.project.entity.sys.Role;
import com.project.entity.sys.User;
import com.project.service.sys.DepartmentService;
import com.project.service.sys.UserService;
import com.project.util.CurrentSessionUtil;
import com.project.util.EncryptString;
import com.project.interceptor.PreventDuplicatesToken;


/**
 * UserController
 * @author
 *
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController<User>{
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	public ConfigBean configBean;
	
	@Autowired
	private DepartmentService departmentService;
	
	@Autowired
	private EncryptString encryptString;
	
	@Autowired
	private CacheService cacheService;
	
	/**
	 * 系统 用户列表
	 * @param model
	 * @param request
	 * @param page
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="list")
	@RequiresPermissions("user:list")
	public String list(Model model,HttpServletRequest request,@ModelAttribute User user) throws Exception{
		user.setcOrder(Order.asc("id"));
	
		if(user.getDepartment()!=null&&user.getDepartment().getId()!=null){
			Department dept = departmentService.getById(user.getDepartment().getId());
			user.getDepartment().setId(dept.getId());
		}
		
		model.addAttribute("page", userService.queryPage(user));
		
		String deptTree = departmentService.queryList();
		model.addAttribute("deptTree", deptTree);
		
		model.addAttribute("systemCode", configBean.getSystemCode());
		
		return "/user/userList";
	}
	
	/**
	 * 新增用户init
	 * @param model
	 * @param request
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="addInit")
	@RequiresPermissions("user:add")
	@PreventDuplicatesToken(save=true)
	public String addInit(Model model,HttpServletRequest request) throws Exception{
		List<Role> roles = userService.queryRolesByStatus();
		model.addAttribute("roles", roles);
		
		String deptTree = departmentService.queryList();
		model.addAttribute("deptTree", deptTree);
		
		model.addAttribute("provinceList", cacheService.getProvinceList());
		
		return "/user/addUser";
	}
	

    /**
	 * 新增用户
	 * @param model
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value="add")
	@RequiresPermissions("user:add")
	@ResponseBody
	@PreventDuplicatesToken(remove=true)
	public String add(Model model,HttpServletRequest request,@ModelAttribute User user)throws Exception{
		String roleIds = request.getParameter("roleValueId");
		
		String rightsValueId = request.getParameter("rightsValueId");
		
		if(user.getDept() != null){
			Department dept = departmentService.getById(Long.parseLong(user.getDept()));
			user.setDept(dept.getCode());
		}
		
		userService.save(user,roleIds,rightsValueId);
		return "true";
	}
	
	/**
	 * 修改系统用户Init
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="updateInit")
	@RequiresPermissions("user:update")
	public String updateInit(Model model,HttpServletRequest request) throws Exception{
		List<Role> allRoles = userService.queryRolesByStatus();
		List<Role> possessRole = getEntity().getRoles();
		allRoles.removeAll(possessRole);
		model.addAttribute("unownedRole",allRoles);
		
		String deptTree = departmentService.queryList();
		model.addAttribute("deptTree", deptTree);
		
//		String deptCode = getEntity().getDept();
//		Department department = departmentService.findByCode(deptCode);
//		getEntity().setDepartment(department);
		
		model.addAttribute("provinceList", cacheService.getProvinceList());
		
		return "/user/updateUser";
	} 
	
	/**
	 * 修改系统用户
	 * @param model
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping("update")
	@RequiresPermissions("user:update")
	@ResponseBody
	public String update(@ModelAttribute(value="entity") User entity, HttpServletRequest request)throws Exception{
		String roleIds = request.getParameter("roleValueId");
		String deptId = request.getParameter("deptId");
		
		String rightsValueId = request.getParameter("rightsValueId");
		
		if(StringUtils.isNotEmpty(deptId)){
			Department dept = departmentService.getById(Long.parseLong(deptId));
			entity.setDept(dept.getCode());
		}
		
		userService.update(entity,roleIds,rightsValueId);
		return "true";
	}
	
	/**
	 * ajax删除user对象
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="delete")
	@RequiresPermissions("user:delete")
	@ResponseBody
	public String delete(HttpServletRequest request)throws Exception{
		User user = getEntity();
		
		if(!user.getUserCode().equals(configBean.getSystemCode())){
			userService.delete(user);
			return "true";
		}else{
			return "false";
		}
		
	}
	
	/**
	 * ajax验证用户名是否重复
	 * @param request
	 * @return
	 */
	@RequestMapping(value="repetitionValidate")
	@ResponseBody
	public String repetitionValidate(HttpServletRequest request)throws Exception{
		String userCode = request.getParameter("userCode");
		User user = userService.getByUsername(userCode);
		
		if(user == null){
			return "true";
		}else{
			return "false";
		}
	}
	
	/**
	 * 查看用户
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value="view")
	@RequiresPermissions("user:view")
	public String view(Model model,HttpServletRequest request){
		return "/user/viewUser";
	}
	
	/**
	 * 启用/禁用
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="doED")
	@RequiresPermissions("user:erduser")
	@ResponseBody
	public String doED(HttpServletRequest request)throws Exception{
		String status = request.getParameter("status");
		User user = getEntity();
		
		userService.doEd(user, status);
		return "true";
	}
	
	@RequestMapping(value="resetPwd")
	@RequiresPermissions("user:resetPassword")
	@ResponseBody
	public String resetPwd(HttpServletRequest request)throws Exception{
		String ids = request.getParameter("ids");
		
		return userService.resetPwd(ids);
	}
	
	
	@RequestMapping(value="ajaxlist")
	@RequiresPermissions("user:list")
	@ResponseBody
	public List<User> list(Model model,@ModelAttribute User user) throws Exception{
		List<User> list = userService.query(user);
		List<User> l = new ArrayList<>();
		for (User u : list) {
			User user2 = new User();
			user2.setId(u.getId());
			user2.setName(u.getName());
			l.add(user2);
		}
		return l;
	}
	
	/**
     * 验证密码是否相同
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="passWordOldSame")
	@ResponseBody
	public String passWordOldSame(HttpServletRequest request,@ModelAttribute UserPwd userPwd)throws Exception{
    	User user=CurrentSessionUtil.getCurrentUser();
    	String oldPassWord=user.getPassword();
    	String passWord=userPwd.getOldPassword();
    	String pwd =  encryptString.MD5Encrypt(passWord);
    	if(pwd.equals(oldPassWord)){
    		return "true";
    	}else{
    		return "false";
    	}
    	
	}
	
	/**
     * 修改密码
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="updatePwd")
	public String updatePwd(HttpServletRequest request)throws Exception{	
		return "/user/updatePassWord";
	}
    
    /**
     * 保存修改的密码
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="updatePwdWord")
	@ResponseBody
	public String pwd(HttpServletRequest request,@ModelAttribute UserPwd userPwd)throws Exception{
    	return userService.updatePwd(userPwd);
	}
    
    
    
	@Override
	protected Class<User> getClazz() {
		return User.class;
	}
	
}
